﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using DTO;
using BLL;
using DevExpress.XtraTreeList.StyleFormatConditions;

namespace CRM.GUI.QLHeThong
{
    public partial class ucBrand : UserControl
    {
        public ucBrand()
        {
            InitializeComponent();
            treeBrand.BestFitColumns();
            sptBrand.Panel2Collapsed = true;
            IntialLoad();
        }
        private BrandEntity _Brand;
        private List<BrandEntity> _list;
        private int addcase = 0;
        private int expand = 0;
        private int index = -1;

        private void IntialLoad()
        {
            _list = SharedData.BrandList;
            treeBrand.KeyFieldName = "Brand_ID";
            treeBrand.ParentFieldName = "Parent_Code";
            treeBrand.DataSource = _list;
            cmbRootBrand.Properties.DataSource = _list;
            cmbRootBrand.Properties.DisplayMember = "Brand_Code";
            cmbRootBrand.Properties.ValueMember = "Brand_ID";

        }

        private void mbtnAddRoot_Click(object sender, EventArgs e)
        {
            addcase = 1;
            sptBrand.Panel2Collapsed = false;
            btnAddBrand.Text = "Thêm";
            txtBrandCode.Focus();
        }

        private void mbtnAddChild_Click(object sender, EventArgs e)
        {
            addcase = 2;
            grbBrand.Text = "Thêm nhãn sữa con";
            btnAddBrand.Text = "Thêm";
            sptBrand.Panel2Collapsed = false;
            cmbRootBrand.EditValue = _Brand.Brand_ID;
            txtBrandCode.Focus();
        }

        private void mbtnUpdateNode_Click(object sender, EventArgs e)
        {
            addcase = 3;
            grbBrand.Text = "Cập nhật nhãn sữa";
            btnAddBrand.Text = "Cập nhật";
            cmbRootBrand.Enabled = true;
            sptBrand.Panel2Collapsed = false;
            ShowInfo();
            txtBrandCode.Focus();
        }

        private void btnAddBrand_Click(object sender, EventArgs e)
        {
            CheckInput();
            cDataInTransfer data = new cDataInTransfer();
            BrandEntity br = new BrandEntity();
            string errmessage = "Có lỗi xảy ra trong quá trình thực hiện\nXin vui lòng thực hiện lại.";
            switch (addcase)
            {
                case 0:
                    return;

                case 1:
                    br.Brand_Code = txtBrandCode.Text.Trim();
                    br.BrandName = txtBrandName.Text.Trim();
                    br.BrandLevel = 1;
                    br.Description = txtBrandDescription.Text.Trim();
                    br.Parent_Code = 0;
                    try
                    {
                        data.AddNewBrand(br, "root");
                        MessageBox.Show("Thêm mới thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch
                    {
                        MessageBox.Show(errmessage, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case 2:
                    br.Brand_Code = txtBrandCode.Text.Trim();
                    br.BrandName = txtBrandName.Text.Trim();
                    br.BrandLevel = _Brand.BrandLevel + 1;
                    br.Description = txtBrandDescription.Text.Trim();
                    br.Parent_Code = _Brand.Brand_ID;
                    try
                    {
                        data.AddNewBrand(br, "child");
                        MessageBox.Show("Thêm mới thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch
                    {
                        MessageBox.Show(errmessage, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case 3:                    
                    br.Brand_ID = _Brand.Brand_ID;
                    br.Brand_Code = txtBrandCode.Text.Trim();
                    br.BrandName = txtBrandName.Text.Trim();
                    br.Description = txtBrandDescription.Text.Trim();
                    var parentbrand = (BrandEntity)searchLookUpEdit1View.GetFocusedRow();
                    if (cmbRootBrand.EditValue != null) //Child
                    {
                        if (_Brand.BrandLevel < parentbrand.BrandLevel)
                        {
                            br.Parent_Code = parentbrand.Brand_ID;
                            br.BrandLevel = parentbrand.BrandLevel + 1;
                            childlist.Add(br);                            
                            childlist[0].Parent_Code = 0;
                            childlist[0].BrandLevel = 1;
                            int startlvl = childlist[0].BrandLevel;
                            foreach (BrandEntity item in childlist)
                            {
                                if (item.BrandLevel != 1)
                                {
                                    startlvl++;
                                    if (item.Brand_ID == _Brand.Brand_ID)
                                    {
                                        item.BrandLevel = childlist.Where(a => a.Brand_ID == parentbrand.Brand_ID).SingleOrDefault().BrandLevel + 1;
                                    }
                                    else
                                    {
                                        item.BrandLevel = startlvl;
                                    }                                    
                                    data.UpdateBrand(item);
                                }
                                else
                                {
                                    data.UpdateBrand(item);
                                }
                            }
                            
                        }
                        else
                        {
                            br.BrandLevel = SharedData.BrandList.Where(a => a.Brand_ID == (int)cmbRootBrand.EditValue).SingleOrDefault().BrandLevel + 1;
                            br.Parent_Code = (int)cmbRootBrand.EditValue;
                        }
                    }
                    else                                       
                    {   //root
                        br.BrandLevel = 1;
                        br.Parent_Code = 0;
                    }                    
                    
                    try
                    {
                        if (_Brand.BrandLevel > parentbrand.BrandLevel || cmbRootBrand.EditValue == null)
                        {
                            data.UpdateBrand(br);
                        }               
                        MessageBox.Show("Cập nhật thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch
                    {
                        MessageBox.Show(errmessage, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
            }
            txtBrandCode.Text = null;
            txtBrandName.Text = null;
            txtBrandDescription.Text = null;
            _list = data.LoadListBrand();
            SharedData.BrandList = _list;
            treeBrand.DataSource = _list;
            cmbRootBrand.Properties.DataSource = _list;
            ExpandAndCollapse();
            treeBrand.FocusedNode = treeBrand.FindNodeByID(index);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            sptBrand.Panel2Collapsed = true;
            txtBrandCode.Text = null;
            txtBrandName.Text = null;
            txtBrandDescription.Text = null;
        }
        private List<BrandEntity> childlist = new List<BrandEntity>();
        private void treeBrand_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            _Brand = (BrandEntity)treeBrand.GetDataRecordByNode(e.Node);
            int i = _Brand.Brand_ID;
            index = e.Node.Id;
            childlist.Clear();
            int count = SharedData.BrandList.Where(a => a.Parent_Code == i).ToList().Count;
            while (e.Node.HasChildren && count > 0 )    // lay danh sach cac node con lien quan
            {
                count = SharedData.BrandList.Where(a => a.Parent_Code == i).ToList().Count;
                foreach (BrandEntity item in SharedData.BrandList.Where(a => a.Parent_Code == i).ToList())
                {
                    childlist.Add(item);
                    i = (int)item.Brand_ID;            
                }
            }
            ShowInfo();
        }

        private void CheckInput()
        {
            if (string.IsNullOrWhiteSpace(txtBrandCode.Text))
            {
                MessageBox.Show("Mã nhãn sữa không được để trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                addcase = 0;
                return;
            }
            if (string.IsNullOrWhiteSpace(txtBrandName.Text))
            {
                MessageBox.Show("Tên nhãn sữa không được để trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                addcase = 0;
                return;
            }
        }

        private void mbtnExpand_Click(object sender, EventArgs e)
        {
            if (mbtnExpand.CheckState == CheckState.Checked)
            {
                treeBrand.ExpandAll();
                expand = 1;
                mbtnCollapse.CheckState = CheckState.Unchecked;
            }
        }

        private void mbtnCollapse_Click(object sender, EventArgs e)
        {
            if (mbtnCollapse.CheckState == CheckState.Checked)
            {
                treeBrand.CollapseAll();
                expand = 0;
                mbtnExpand.CheckState = CheckState.Unchecked;
            }
        }

        private void ExpandAndCollapse()
        {
            if (expand == 1)
            {
                treeBrand.ExpandAll();
            }
            else
            {
                treeBrand.CollapseAll();
            }
        }

        private void treeBrand_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DevExpress.XtraTreeList.TreeList tree = sender as DevExpress.XtraTreeList.TreeList;
                DevExpress.XtraTreeList.TreeListHitInfo hitInfo = tree.CalcHitInfo(e.Location);
                _Brand = (BrandEntity)treeBrand.GetDataRecordByNode(hitInfo.Node);
                if (_Brand == null)
                {
                    mbtnAddChild.Enabled = false;
                    mbtnUpdateNode.Enabled = false;
                }
                else
                {
                    mbtnAddChild.Enabled = true;
                    mbtnUpdateNode.Enabled = true;
                }
            }
        }

        private void ShowInfo()
        {
            if (addcase > 1)
            {
                if (_Brand.Parent_Code != 0)
                {
                    cmbRootBrand.Enabled = true;
                    cmbRootBrand.EditValue = _Brand.Parent_Code;
                    txtBrandCode.Text = _Brand.Brand_Code;
                    txtBrandName.Text = _Brand.BrandName;
                    txtBrandDescription.Text = _Brand.Description;
                }
                else
                {
                    cmbRootBrand.Enabled = false;
                    cmbRootBrand.EditValue = null;
                    txtBrandCode.Text = _Brand.Brand_Code;
                    txtBrandName.Text = _Brand.BrandName;
                    txtBrandDescription.Text = _Brand.Description;
                }
            }
        }

        private void OnTextChanged()
        {
            if (addcase > 1)
            {
                if (cmbRootBrand.EditValue != null)
                {
                    if ((int)cmbRootBrand.EditValue != _Brand.Parent_Code || txtBrandCode.Text != _Brand.Brand_Code.ToString() ||
                        txtBrandName.Text != _Brand.BrandName.ToString() ||
                        txtBrandDescription.Text != _Brand.Description)
                    {
                        btnAddBrand.Enabled = true;
                    }
                    else
                    {
                        btnAddBrand.Enabled = false;
                    }
                }
                else
                {
                    if (txtBrandCode.Text != _Brand.Brand_Code.ToString() ||
                        txtBrandName.Text != _Brand.BrandName.ToString() ||
                        txtBrandDescription.Text != _Brand.Description.ToString())
                    {
                        btnAddBrand.Enabled = true;
                    }
                    else
                    {
                        btnAddBrand.Enabled = false;
                    }
                }
            }
        }

        private void cmbRootBrand_Click(object sender, EventArgs e)
        {
            cmbRootBrand.Properties.DataSource = _list.Where(a => a.Brand_ID != _Brand.Brand_ID).ToList();
        }

        private void txtBrandCode_TextChanged(object sender, EventArgs e)
        {
            OnTextChanged();
        }

        private void cmbRootBrand_EditValueChanged(object sender, EventArgs e)
        {
            OnTextChanged();
        }

        private void txtBrandName_TextChanged(object sender, EventArgs e)
        {
            OnTextChanged();
        }

        private void txtBrandDescription_TextChanged(object sender, EventArgs e)
        {
            OnTextChanged();
        }

        private void mbtnDone_Click(object sender, EventArgs e)
        {
            sptBrand.Panel2Collapsed = true;
            txtBrandCode.Text = null;
            txtBrandName.Text = null;
            txtBrandDescription.Text = null;
        }

        private void treeBrand_CellValueChanging(object sender, DevExpress.XtraTreeList.CellValueChangedEventArgs e)
        {
            cDataInTransfer data = new cDataInTransfer();
            index = e.Node.Id;
            _Brand = (BrandEntity)treeBrand.GetDataRecordByNode(e.Node);
            childlist.Add(_Brand);
            if (e.Column.AbsoluteIndex == treeBrand.Columns["IsCustomer"].AbsoluteIndex)
            {                
                foreach (BrandEntity item in childlist)
                {
                    item.IsCustomer = (bool)e.Value;
                    data.UpdateBrandStatus(item, "IsCustomer");
                }                
            }
            else if (e.Column.AbsoluteIndex == treeBrand.Columns["IsDisable"].AbsoluteIndex)
            {
                foreach (BrandEntity item in childlist)
                {
                    item.IsDisable = (bool)e.Value;
                    data.UpdateBrandStatus(item, "IsDisable");
                }                
            }
            _list = data.LoadListBrand();
            SharedData.BrandList = _list;
            treeBrand.DataSource = _list;
            cmbRootBrand.Properties.DataSource = _list;
            ExpandAndCollapse();
            treeBrand.FocusedNode = treeBrand.FindNodeByID(index);
            
        }

    }
}
